//
//  ALCameraViewController.m
//  hihuasheng
//
//  Created by anlun on 15/9/10.
//  Copyright (c) 2015年 anLun. All rights reserved.
//

#import "ALCameraViewController.h"
#import <AVFoundation/AVCaptureSession.h>
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVCaptureInput.h>
#import <AVFoundation/AVCaptureOutput.h>
#import <AVFoundation/AVMediaFormat.h>
#import "ALUtilsMacro.h"

@interface ALCameraViewController ()
@property(nonatomic,retain)AVCaptureSession * AVSession;
@end

@implementation ALCameraViewController

- (void)viewDidLoad {
	[super viewDidLoad];
	self.delegate = self;
}

#pragma mark get/show the UIView we want
- (UIView *)findView:(UIView *)aView withName:(NSString *)name {
	Class cl = [aView class];
	NSString *desc = [cl description];
	if ([name isEqualToString:desc])
		return aView;
	for (NSUInteger i = 0; i < [aView.subviews count]; i++) {
		UIView *subView = [aView.subviews objectAtIndex:i];
		subView = [self findView:subView withName:name];
		if (subView)
			return subView;
	}
	return nil;
}

#pragma mark UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
	if(self.sourceType == UIImagePickerControllerSourceTypeCamera){
		[self setShowsCameraControls:NO];
		
		UIView *overlyView = [[UIView alloc]
							  initWithFrame:CGRectMake(0, 0, AL_ScreenWidth, AL_ScreenHeight)];
		
		UIView *topView=[[UIView alloc]
						 initWithFrame:CGRectMake(0, 0, AL_ScreenWidth, (40+88)/2)];
		[topView setBackgroundColor:[UIColor whiteColor]];
		[overlyView addSubview:topView];
		
		UIButton * btnClose=[UIButton buttonWithType:UIButtonTypeCustom];
		[btnClose setFrame:CGRectMake(40/2,
									  (topView.frame.size.height-26/2)/2+20/2,
									  26/2,
									  26/2)];
		[btnClose addTarget:self
					 action:@selector(btnAction:)
		   forControlEvents:UIControlEventTouchUpInside];
		[btnClose setTag:kTagButtonClose];
		[btnClose setImage:[UIImage imageNamed:@"CameraPicker.bundle/Camera_Close"] forState:UIControlStateNormal];
		[btnClose setTag:kTagButtonClose];
		[topView addSubview:btnClose];
		
		float top=topView.frame.origin.y+topView.frame.size.height+750/2+15;
		UIView *bottomView=[[UIView alloc]
							initWithFrame:CGRectMake(0, top+AL_NavigationBarHeight, AL_ScreenWidth, AL_ScreenHeight-top)];
		[bottomView setAlpha:.5f];
		[bottomView setBackgroundColor:[UIColor whiteColor]];
		[overlyView addSubview:bottomView];
		
		UIButton *guidBtn=[UIButton buttonWithType:UIButtonTypeCustom];
		[guidBtn setFrame:CGRectMake(20/2, 20/2, 41/2, 41/2)];
		[guidBtn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
		[guidBtn setImage:[UIImage imageNamed:@"CameraPicker.bundle/Grid"] forState:UIControlStateNormal];
		[guidBtn setTag:kTagGrid];
		[bottomView addSubview:guidBtn];
		
		UIButton *switchBtn=[UIButton buttonWithType:UIButtonTypeCustom];
		[switchBtn setFrame:CGRectMake((AL_ScreenWidth-51/2)/2, 20/2, 51/2, 54/2)];
		[switchBtn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
		[switchBtn setImage:[UIImage imageNamed:@"CameraPicker.bundle/Switch"] forState:UIControlStateNormal];
		[switchBtn setTag:kTagSwitch];
		[bottomView addSubview:switchBtn];
		
		UIButton *flashBtn=[UIButton buttonWithType:UIButtonTypeCustom];
		[flashBtn setFrame:CGRectMake(AL_ScreenWidth-51/2*2, 20/2, 51/2, 54/2)];
		[flashBtn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
		[flashBtn setImage:[UIImage imageNamed:@"CameraPicker.bundle/flash"] forState:UIControlStateNormal];
		[flashBtn setTag:kTagFlash];
		[bottomView addSubview:flashBtn];
		
		UIView *bottomGradView=[[UIView alloc] initWithFrame:CGRectMake(0, 90/2,AL_ScreenWidth, bottomView.frame.size.height-90/2)];
		[bottomGradView setBackgroundColor:[UIColor grayColor]];
		[bottomView addSubview:bottomGradView];
		
		UIButton *takeBtn=[UIButton buttonWithType:UIButtonTypeCustom];
		[takeBtn setFrame:CGRectMake((AL_ScreenWidth-179/2)/2, (bottomGradView.frame.size.height-179/2)/2, 179/2, 179/2)];
		[takeBtn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
		[takeBtn setImage:[UIImage imageNamed:@"CameraPicker.bundle/takePicture"] forState:UIControlStateNormal];
		[takeBtn setTag:kTagTakePicture];
		[bottomGradView addSubview:takeBtn];
		
		self.cameraOverlayView = overlyView;
	}
}
#pragma mark - ButtonAction Methods
- (IBAction)swapFrontAndBackCameras:(id)sender {
	if (self.cameraDevice ==UIImagePickerControllerCameraDeviceRear ) {
		self.cameraDevice = UIImagePickerControllerCameraDeviceFront;
	}else {
		self.cameraDevice = UIImagePickerControllerCameraDeviceRear;
	}
}

- (void)closeView
{
	[self dismissModalViewControllerAnimated:YES];
}

- (void)takePicture
{
	[super takePicture];
}

- (void)showPhoto
{
	[[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
	[self setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

#pragma mark Camera View Delegate Methods
- (void)imagePickerController:(UIImagePickerController *)picker
didFinishPickingMediaWithInfo:(NSDictionary *)info
{
	UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
	
	[picker dismissViewControllerAnimated:NO completion:^{
		[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque animated:YES];
		if (self.theSuccessBlock) {
			self.theSuccessBlock(self,image);
		}
	}];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
	[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque animated:YES];
	[picker dismissModalViewControllerAnimated:YES];
}

- (void)btnAction:(id)sender{
	UIButton *btn=sender;
	switch (btn.tag) {
		case kTagButtonClose:
		{
			if (self.theCancelBlock) {
				self.theCancelBlock(self);
			}
			[self dismissViewControllerAnimated:YES completion:^{
			}];
			break;
		}
		case kTagGrid:
		{
#warning 这里需要做
			break;
		}
		case kTagSwitch:
		{
			if (self.cameraDevice ==UIImagePickerControllerCameraDeviceRear ) {
				self.cameraDevice = UIImagePickerControllerCameraDeviceFront;
			}else {
				self.cameraDevice = UIImagePickerControllerCameraDeviceRear;
			}
			break;
		}
		case kTagFlash:
		{
			[self openFlashlight];
			break;
		}
		case kTagTakePicture:
		{
			[self takePicture];
			break;
		}
  default:
			break;
	}
}
/**
 *  打开闪光灯
 */
-(void)openFlashlight
{
	AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
	if (device.torchMode == AVCaptureTorchModeOff) {
		//Create an AV session
		AVCaptureSession * session = [[AVCaptureSession alloc]init];
		// Create device input and add to current session
		AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
		[session addInput:input];
		// Create video output and add to current session
		AVCaptureVideoDataOutput * output = [[AVCaptureVideoDataOutput alloc]init];
		[session addOutput:output];
		// Start session configuration
		[session beginConfiguration];
		[device lockForConfiguration:nil];
		// Set torch to on
		[device setTorchMode:AVCaptureTorchModeOn];
		[device unlockForConfiguration];
		[session commitConfiguration];
		// Start the session
		[session startRunning];
		// Keep the session around
		[self setAVSession:self.AVSession];
	}
}
/**
 *  关闭闪光灯
 */
-(void)closeFlashlight
{
	[self.AVSession stopRunning];
}
@end
